<template>
  <div class="questionCenter">
    <!-- 新增、修改试题 -->
    <changeQuestion
      :treeList="treeList"
      ref="changeQuestionpage"
      @closeBTN="btnBack"
      @init="getQuestion()"
      v-show="showChangeQuestion"
    />
    <!-- 新增、修改试题 -->
    <div v-show="!showChangeQuestion">
      <el-row type="flex" justify="end" style="padding: 15px 0">
        <el-col :span="2" :offset="0">
          <el-button
            type="primary"
            plain
            size="small"
            @click="btnChangeQuesting('add', tableData[0])"
            >新增试题</el-button
          >
        </el-col>
      </el-row>
      <!-- 第一行 -->
      <el-row>
        <el-col :span="6" :offset="0">
          <span class="text">学科名称</span>
          <el-select
            v-model="questionList.subject_id"
            placeholder="请选择学科"
            size="small"
            clearable
          >
            <el-option
              v-for="item in treeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="6" :offset="0">
          <span class="text">目录名称</span>
          <el-select
            v-model="questionList.directory_id"
            placeholder="请选择目录"
            size="small"
            clearable
          >
            <el-option
              v-for="item in directory_id"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="6" :offset="0">
          <span class="text">标签名称</span>
          <el-select
            v-model="questionList.tag_id"
            placeholder="请选择标签"
            size="small"
            clearable
          >
            <el-option
              v-for="item in tag_id"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="6" :offset="0">
          <span class="text">试题类型</span>
          <el-select
            v-model="questionList.quest_type"
            placeholder="请选择题型"
            size="small"
            clearable
          >
            <el-option
              v-for="item in quest_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <!-- 第二行 -->
      <el-row>
        <el-col :span="6" :offset="0">
          <span class="text">审核状态</span>
          <el-select
            v-model="questionList.check_state"
            placeholder="请选择审核状态"
            size="small"
            clearable
          >
            <el-option
              v-for="item in check_state"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="6" :offset="0">
          <span class="text">发布状态</span>
          <el-select
            v-model="questionList.show_state"
            placeholder="请选择发布状态"
            size="small"
            clearable
          >
            <el-option
              v-for="item in show_state"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="6" :offset="0">
          <span class="text">创建者</span>
          <el-input
            placeholder="请输入创建者"
            style="width: 206px"
            size="small"
            v-model="questionList.create_name"
          ></el-input>
        </el-col>
        <el-col :span="6" :offset="0">
          <span class="text">试题难度</span>
          <el-select
            v-model="questionList.difficulty"
            placeholder="请选择难度"
            size="small"
            clearable
          >
            <el-option
              v-for="item in difficulty"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <!-- 第三行 -->
      <el-row>
        <el-col :span="6" :offset="0">
          <span class="text">是否真题</span>
          <el-select
            v-model="questionList.is_true_question"
            placeholder="请选择是否真题"
            size="small"
            clearable
          >
            <el-option
              v-for="item in is_true_question"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="8" :offset="0">
          <span class="text">创建时间</span>
          <el-date-picker
            v-model="questionList.create_time"
            size="small"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-col>
        <el-col :span="10" :offset="0">
          <el-row type="flex" justify="end">
            <el-button type="primary" @click="getQuestion()" size="small"
              >查询</el-button
            >
            <el-button
              size="small"
              @click="
                questionList = {
                  page: 1,
                  limit: 10,
                  subject_id: '',
                  directory_id: '',
                  tag_id: '',
                  difficulty: '',
                  quest_type: '',
                  is_true_question: '',
                  show_state: '',
                  check_state: '',
                  create_name: '',
                  create_time: '',
                }
              "
              >重置</el-button
            >
            <el-button
              size="small"
              @click="
                showIcon =
                  showIcon === 'el-icon-folder-add'
                    ? 'el-icon-folder-remove'
                    : 'el-icon-folder-add'
              "
              type="warning"
              :icon="showIcon"
            ></el-button>
          </el-row>
        </el-col>
      </el-row>
      <!-- 批量操作按钮区域 -->
      <el-row v-if="multipleSelection.length > 0">
        <el-button type="success" size="small" @click="batch(1)"
          >批量上架</el-button
        >
        <el-button type="warning" size="small" @click="batch(2)"
          >批量下架</el-button
        >
        <el-button type="primary" size="small" @click="batch(3)"
          >批量通过</el-button
        >
      </el-row>
      <!-- 表格区域 -->
      <el-table
        ref="multipleTable"
        border
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="80px" align="center">
        </el-table-column>
        <!-- 试题信息区域 -->
        <el-table-column prop="name" label="试题信息">
          <template slot-scope="{ row }">
            <!-- 第一行 -->
            <el-row>
              <el-col :span="2" :offset="0">
                <span class="textItem">ID:</span>
                {{ row.id }}
              </el-col>
              <el-col :span="22" :offset="0">
                <el-row type="flex" class="questionTitle">
                  <span class="textItem">题干信息:</span>
                  <el-link
                    type="primary"
                    v-html="row.question"
                    :underline="false"
                    @click="btnDetails(row)"
                  ></el-link>
                </el-row>
              </el-col>
            </el-row>
            <!-- 第二行 -->
            <el-row>
              <el-col
                :span="8"
                :offset="0"
                v-show="showIcon === 'el-icon-folder-add'"
              >
                <span class="textItem">试题编号:</span>
                {{ row.quest_num }}
              </el-col>
              <el-col
                :span="6"
                :offset="0"
                v-show="showIcon === 'el-icon-folder-add'"
              >
                <span class="textItem">试题类型:</span>
                {{
                  row.quest_type === 4
                    ? "简答题"
                    : row.quest_type === 3
                    ? "判断题"
                    : row.quest_type === 2
                    ? "多选题"
                    : "单选题"
                }}
              </el-col>
              <el-col :span="6" :offset="0">
                <span class="textItem">归属学科:</span>
                {{ row.subject_name }}
              </el-col>
              <el-col :span="4" :offset="0">
                <span class="textItem">归属目录:</span>
                {{ row.directory_name }}
              </el-col>
            </el-row>
            <!-- 第三行 -->
            <el-row>
              <el-col :span="8" :offset="0">
                <span class="textItem">标签信息:</span>
                {{ row.tag_info[0] }}
              </el-col>
              <el-col :span="6" :offset="0">
                <span class="textItem">发布状态:</span>
                <el-button
                  :type="row.show_state === 2 ? 'info' : 'success'"
                  disabled
                  plain
                  size="mini"
                >
                  {{ row.show_state === 1 ? "上架" : "下架" }}</el-button
                >
              </el-col>
              <el-col
                :span="6"
                :offset="0"
                v-show="showIcon === 'el-icon-folder-add'"
              >
                <span class="textItem">审核人:</span>
                暂无
              </el-col>
              <el-col
                :span="4"
                :offset="0"
                v-show="showIcon === 'el-icon-folder-add'"
              >
                <span class="textItem">审核状态:</span>
                <el-button
                  :type="
                    row.check_state === 3
                      ? 'danger'
                      : row.check_state === 2
                      ? 'success'
                      : 'warning'
                  "
                  disabled
                  plain
                  size="mini"
                >
                  {{
                    row.check_state === 3
                      ? "不通过"
                      : row.check_state === 2
                      ? "通过"
                      : "待审核"
                  }}</el-button
                >
              </el-col>
            </el-row>
            <!-- 第四行 -->
            <el-row>
              <el-col
                :span="8"
                :offset="0"
                v-show="showIcon === 'el-icon-folder-add'"
              >
                <span class="textItem">审核意见:</span>
                {{ row.check_remarks === null ? "暂无" : row.check_remarks }}
              </el-col>
              <el-col
                :span="6"
                :offset="0"
                v-show="showIcon === 'el-icon-folder-add'"
              >
                <span class="textItem">创建人:</span>
                {{ row.create_name }}
              </el-col>
              <el-col
                :span="6"
                :offset="0"
                v-show="showIcon === 'el-icon-folder-add'"
              >
                <span class="textItem">难度:</span>
                {{
                  row.difficulty === 3
                    ? "困难"
                    : row.difficulty === 2
                    ? "中等"
                    : "简单"
                }}
              </el-col>
              <el-col :span="4" :offset="0">
                <span class="textItem">发布时间:</span>
                {{ row.created_at | formatDate }}
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="操作"
          width="160px"
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="{ row }">
            <el-row>
              <el-col :span="12" :offset="0">
                <el-link
                  v-if="row.check_state !== 3"
                  icon="el-icon-edit"
                  :underline="false"
                  type="primary"
                  class="linkIcon"
                  @click="btnChange(row)"
                  >{{
                    row.check_state === 1
                      ? "审核"
                      : row.show_state === 1
                      ? "下架"
                      : "上架"
                  }}</el-link
                >
              </el-col>
              <el-col :span="12" :offset="0" v-if="row.show_state === 2">
                <el-link
                  icon="el-icon-edit"
                  :underline="false"
                  type="primary"
                  class="linkIcon"
                  @click="btnChangeQuesting('edit', row)"
                  >修改</el-link
                >
              </el-col>
              <el-col :span="12" :offset="0" v-if="row.show_state === 2">
                <el-link
                  icon="el-icon-delete"
                  :underline="false"
                  type="primary"
                  class="linkIcon"
                  @click="delBtn(row.id)"
                  >删除</el-link
                >
              </el-col>
            </el-row>
            <!-- 审核弹框 -->
            <checkDialog ref="CheckDLG" @initData="getQuestion()" />
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" class="pagination-cts">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage4"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalNum"
        >
        </el-pagination>
      </el-row>
      <!-- 问题详情弹窗 -->
      <questionDetail ref="questDetail" />
    </div>
  </div>
</template>

<script>
import changeQuestion from "./components/changeQuestion.vue";
import questionDetail from "./components/questionDetail.vue";
import checkDialog from "./components/checkDialog.vue";
import {
  getQuestion,
  getQuestionTree,
  isShowQuestion,
  delQuestion,
  AllShowQuestion,
  AllCheckQuestion,
} from "@/api/exam";
export default {
  name: "question",
  components: {
    checkDialog,
    questionDetail,
    changeQuestion,
  },
  data() {
    return {
      // repetId: 0,
      showChangeQuestion: false,
      multipleSelection: [],
      tableData: [],
      value: [],
      options: [],
      showIcon: "el-icon-folder-add",
      quest_type: [
        { label: "单选题", value: 1 },
        { label: "多选题", value: 2 },
        { label: "判断题", value: 3 },
        { label: "简答题", value: 4 },
      ],
      check_state: [
        { label: "待审核", value: 1 },
        { label: "审核通过", value: 2 },
        { label: "不通过", value: 3 },
      ],
      show_state: [
        { label: "上架", value: 1 },
        { label: "下架", value: 2 },
      ],
      difficulty: [
        { label: "简单", value: 1 },
        { label: "中等", value: 2 },
        { label: "困难", value: 3 },
      ],
      is_true_question: [
        { label: "是", value: 1 },
        { label: "否", value: 2 },
      ],
      questionList: {
        page: 1,
        limit: 10,
        subject_id: "",
        directory_id: {},
        tag_id: "",
        difficulty: "",
        quest_type: "",
        is_true_question: "",
        show_state: "",
        check_state: "",
        create_name: "",
        create_time: "",
      },
      currentPage4: 1,
      totalNum: 0,
      treeList: [],
      selectList: [],
    };
  },
  created() {
    this.getQuestion();
    this.getQuestionTree();
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(val);
    },
    async getQuestion() {
      let str = JSON.stringify(this.questionList);
      str = str.replaceAll('"', "");
      str = str.replaceAll("}", "");
      str = str.replaceAll("{", "");
      str = str.replaceAll(":", "=");
      str = str.replaceAll(",", "&");
      // console.log(str);
      let data = await getQuestion(str);
      // console.log(data);
      this.totalNum = data.total;
      this.tableData = data.list;
    },
    async getQuestionTree() {
      const data = await getQuestionTree();
      // console.log(data);
      this.treeList = data;
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.questionList.limit = val;
      this.getQuestion();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.questionList.page = val;
      this.getQuestion();
    },
    async btnChange(row) {
      if (row.check_state === 1) {
        // 审核按钮
        this.$refs.CheckDLG.showDialog = true;
        this.$refs.CheckDLG.form = {};
        this.$refs.CheckDLG.form.id = row.id;
      } else if (row.show_state === 1) {
        // 下架按钮
        await isShowQuestion(row);
        this.$message.success("下架成功");
        this.getQuestion();
      } else {
        // 上架按钮
        await isShowQuestion(row);
        this.$message.success("上架成功");
        this.getQuestion();
      }
    },
    // 删除功能
    delBtn(id) {
      this.$confirm("确定删除吗, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await delQuestion(id);
          // 更新视图
          this.getQuestion();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 查看试题详情
    btnDetails(data) {
      try {
        if (
          data.id !== this.repetId &&
          data.quest_options &&
          data.quest_type !== 4
        ) {
          // 处理数据
          let res = JSON.parse(data.quest_options);
          data.quest_options = res;
          this.selectList = res;
        }
      } catch (error) {
        console.log(error);
      }
      if (data.id === this.repetId) {
        data.quest_options = this.selectList;
      }
      console.log(data.quest_options);
      this.repetId = data.id;
      this.$refs.questDetail.item = data;
      this.$refs.questDetail.showDialog = true;
      this.$refs.questDetail.showIcon = this.showIcon;

      // console.log(data.quest_options);
    },
    // 批量操作
    batch(num) {
      if (num === 1) {
        this.$confirm(
          `确定批量上架这${this.multipleSelection.length}条数据吗`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(async () => {
            // 批量上架
            let newData = this.multipleSelection.filter((item) => {
              return item.check_state === 2;
            });
            // console.log(newData);
            let id = [];
            newData.forEach((item) => {
              id.push(item.id);
              return id;
            });
            // console.log(id);
            await AllShowQuestion(id, 1);
            this.getQuestion();
            this.$message({
              type: "success",
              message: `成功上架${id.length}条数据`,
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
          });
      } else if (num === 2) {
        // 批量下架
        this.$confirm(
          `确定批量下架这${this.multipleSelection.length}条数据吗`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(async () => {
            // 批量下架
            let newData = this.multipleSelection.filter((item) => {
              return item.check_state === 2;
            });
            // console.log(newData);
            let id = [];
            newData.forEach((item) => {
              id.push(item.id);
              return id;
            });
            // console.log(id);
            await AllShowQuestion(id, 2);
            this.getQuestion();
            this.$message({
              type: "success",
              message: `成功下架${id.length}条数据`,
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
          });
      } else {
        let newDataCheck = this.multipleSelection.filter((item) => {
          return item.check_state === 1;
        });
        // console.log(newDataCheck);
        let checklist = [];
        newDataCheck.forEach((item) => {
          return checklist.push({
            check_remarks: "通过，暂无问题",
            check_state: 2,
            id: item.id,
          });
        });
        this.$confirm(`确定批量通过这${checklist.length}条数据吗`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            // 批量通过
            console.log(checklist);
            await AllCheckQuestion(checklist);
            this.getQuestion();
            this.$message({
              type: "success",
              message: `成功通过${checklist.length}条数据`,
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
          });
      }
    },
    btnChangeQuesting(type, row) {
      // 处理多选问题
      if (row.quest_type === 1 || row.quest_type === 2) {
        this.$refs.changeQuestionpage.code = true;
      }
      this.showChangeQuestion = true;

      this.$refs.changeQuestionpage.questionList = {};

      if (type === "add") {
        // 新增试题
         this.$refs.changeQuestionpage.title = 'add'
        this.$refs.changeQuestionpage.questionList = {
          difficulty: 1,
          directory_id: "",
          is_true_question: 2,
          quest_answer: "",
          quest_options: [],
          quest_remark: "<p></p>",
          quest_type: "",
          question: "<p></p>",
          subject_id: 1,
          tag_id: [],
        };
        this.$refs.changeQuestionpage.code = false;
        // row.difficulty =
        //   row.difficulty === 3
        //     ? "困难"
        //     : row.difficulty === 2
        //     ? "中等"
        //     : "简单";

        // try {
        //   // 处理数据
        //   let res1 = JSON.parse(row.quest_options);
        //   row.quest_options = res1;
        //   this.selectList = res1;
        // } catch (error) {
        //   console.log(error);
        // }
        // row.is_true_question = row.is_true_question === 1 ? "是" : "否";
        // // let ress = JSON.parse(row.quest_options);
        // // row.quest_options = ress;

        // this.$refs.changeQuestionpage.questionList = row;
        //  this.$refs.changeQuestionpage.onceinit()
      } else {
        // 修改试题
        this.$refs.changeQuestionpage.title = 'edit'
        row.difficulty =
          row.difficulty === 3
            ? "困难"
            : row.difficulty === 2
            ? "中等"
            : "简单";

        try {
          // 处理数据
          let ress = JSON.parse(row.quest_options);
          row.quest_options = ress;
          this.selectList = ress;
        } catch (error) {
          console.log(error);
        }
        row.is_true_question = row.is_true_question === 1 ? "是" : "否";
        // let ress = JSON.parse(row.quest_options);
        // row.quest_options = ress;

        this.$refs.changeQuestionpage.questionList = row;

        // item.difficulty === 3
        //   ? "困难"
        //   : item.difficulty === 2
        //   ? "中等"
        //   : "简单";
        // console.log(row);
        this.$refs.changeQuestionpage.onceinit();
        
        // console.log(this.$refs.changeQuestionpage.checkList)
      }
    },
    btnBack() {
      this.showChangeQuestion = false;
      this.$refs.changeQuestionpage.questionList = {};
      this.$refs.changeQuestionpage.tableData = [
        { code: "A", content: "", is_true: false, pic: "" },
        { code: "B", content: "", is_true: false, pic: "" },
        { code: "C", content: "", is_true: false, pic: "" },
        { code: "D", content: "", is_true: false, pic: "" },
      ];
      this.$refs.changeQuestionpage.checkList = [];
    },
  },
  computed: {
    directory_id() {
      let obj = this.treeList.find((item) => {
        return item.id === this.questionList.subject_id;
      });
      // console.log(obj);
      obj = obj || {};
      return obj["children"];
    },
    tag_id() {
      if (!this.directory_id) {
        return [];
      } else {
        // console.log(1);
        let subList = this.questionList.directory_id;

        let obj1 = this.directory_id.find((item) => {
          // console.log(item.id);
          return item.id === subList;
        });
        // console.log(obj1);
        obj1 = obj1 || {};
        return obj1["children"];
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.el-row {
  padding: 5px 20px;
}
.text {
  font-weight: 700;
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
}
.linkIcon {
  font-size: 10px;
}
.textItem {
  color: #aaa;
  margin-right: 5px;
}
.questionTitle {
  align-items: center;
  height: 20px;
}
.pagination-cts {
  padding: 20px 0;
}
.questionCenter {
  background-color: #fff;
}
</style>
